const mysql = require('mysql2/promise');
const {connection} = require('./common');

//获取数据的方法
async function getCulture(){
    let sql = 'select * from culture'
    let res = await connection.execute(sql);
    return JSON.stringify(res[0]);
}

//增加数据的方法
async function addCulture(data){
    let obj = data;
    let str = '';
    let arr = []
    for(let i in obj){
        if(i == 'upload'){
        arr.push('cultureImg')
        if(obj[i].length == 1){
            str = str + `'${obj[i][0].response.addr}',`
        }else{
            let str0 = '';
            for(let j = 0 ; j< obj[i].length;j++){
                str0 = str0 + `${obj[i][j].response.addr};`
            }
            str = str + `'${str0}',`
        }
        }else{
        arr.push(i)
        str = str + `'${obj[i]}',`
        }
    }
    let x = str.slice(0,str.length-1);
    let sql = `INSERT INTO culture(${arr}) VALUES(${x}) `
    await connection.execute(sql); 
    return JSON.stringify("success");
}

//删除数据
async function deleteCluture(data){
    let obj = data;
    let cultureID = obj.cultureID;
    let cityID = obj.cityID;
    let sql = `DELETE FROM culture WHERE cultureID = '${cultureID}' and cityID = '${cityID}'`
    await connection.execute(sql); 
    return JSON.stringify("success");
}
//修改数据
async function putCulture(data){
    let result = data;
    let newObj = result.new;
    let id0 = result.old.cultureID;
    let id1 = result.old.cityID;
    let str = '';
    for(let i in newObj){
      str = str + `${i} = '${newObj[i]}',`
    }
    let x = str.slice(0,str.length-1);
    let sql = `UPDATE culture SET ${x} WHERE cultureID = '${id0}' and cityID = '${id1}'`
    let res = await connection.execute(sql)
    return JSON.stringify('success!')
}

module.exports = {
    getCulture,
    addCulture,
    deleteCluture,
    putCulture
}